/**
 * 
 */
package com.thon.controller.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.thon.commons.config.Global;
import com.thon.commons.utils.Encodes;
import com.thon.security.ShiroDbRealm.ShiroUser;

/**
 * @author manpiaoyi
 * @email manpiaoyi@126.com
 * @date 2014-10-13
 * @description:
 */
public abstract class BaseController {
	private static final Log log = LogFactory.getLog(BaseController.class);
	private static final String REGEX_EMAIL = "^[A-Za-z0-9][\\w\\-\\.]{1,12}@([\\w\\-]+\\.)+[\\w]{2,3}$";
	private static final String REGEX_PHONE = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
	private static final String REGEX_NICKNAME = "^[\u4E00-\u9FA5a-zA-Z0-9]{2,10}$";
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, false));
	}
	
	@ModelAttribute
	public void initVersion(HttpSession session, Model model) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date=new Date();
		model.addAttribute("env", Global.getConfig("env"));
		model.addAttribute("version", Global.getConfig("version"));
		model.addAttribute("img_url", Global.getConfig("img.url"));
		model.addAttribute("admin_url",Encodes.encodeBase64((Global.getConfig("admin.url")+"&"+dateFormat.format(date)).getBytes()));
	}
	
	/**
	 * 返回站点地址
	 * @param request
	 * @return
	 */
	public String getBasePath(HttpServletRequest request){
		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+ request.getContextPath();
	}
	
	
	/**
	 * 页面对象转化为字符串
	 * @param request
	 * @param key
	 * @return
	 */
	public String fmtToString(HttpServletRequest request, String key) {
		log.debug("request will format to string: "+request.getParameter(key));
		
		Object str = request.getParameter(key);
		if (str == null || str =="") {
			return null;
		}
		else {
			return HtmlFliter(str.toString().trim());
		}
	}
	
	/**
	 * Object对象转化为字符串
	 * @param request
	 * @param key
	 * @return
	 */
	public String fmtToString(Object object) {
		log.debug("object will format to string: "+ object);
		
		if (object == null || object =="") {
			return null;
		}
		else {
			return HtmlFliter(object.toString().trim());
		}
	}
	
	/**
	 * Object对象转化为布尔值
	 * @param request
	 * @param key
	 * @return
	 */
	public Boolean fmtToBoolean(Object object) {
		log.debug("object will format to string: "+ object);
		
		if (object == null || object =="") {
			return null;
		}else {
			String temp = object.toString();
			if (temp.equalsIgnoreCase("true") || temp.equalsIgnoreCase("1") || temp.equalsIgnoreCase("yes")) {
				return true;
			}else {
				return false;
			}
		}
	}
	
	/**
	 * 页面对象转化为boolean对象
	 * @param request
	 * @param key
	 * @return
	 */
	public Boolean fmtToBoolean(HttpServletRequest request, String key){
		log.debug("request will format to Boolean: "+request.getParameter(key));
		
		String str = this.fmtToString(request, key);
		
		if (str == null || str =="") {
			return false;
		}
		else {
			if (str.equalsIgnoreCase("true") || str.equalsIgnoreCase("1") || str.equalsIgnoreCase("yes")) {
				return true;
			}else {
				return false;
			}
		}
	}
	
	/**
	 * 页面对象转化为时间对象
	 * @param request
	 * @param key
	 * @return
	 */
	public Date fmtToDate(HttpServletRequest request, String key) {
		log.debug("request will format to date: "+request.getParameter(key));
		
		Object str = request.getParameter(key);
		if (str == null || str =="") {
			return null;
		}
		else {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date paramdDate =null;
			try {
				paramdDate = format.parse(str.toString().trim());
			} catch (ParseException e) {
				log.error(e.getStackTrace());
				return null;
			}
			return paramdDate;
		}
	}
	
	/**
	 * 页面对象转化为时间对象
	 * @param object
	 * @param 
	 * @return
	 */
	public Date fmtToDate(Object object) {
		
		Object str = object;
		if (str == null || str =="") {
			return new Date();
		}else {
			return new Date(fmtToLong(object));
		}
	}
	
	/**
	 * 页面对象转化为短时间对象
	 * @param object
	 * @param 
	 * @return
	 */
	public Date fmtToDateShort(Object object) {
		
		Object str = object;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		
		// 空值返回当期时间
		Date paramdDate =null;
		if (str == null || str =="") {
			return new Date();
		}
		
		try {
			paramdDate = format.parse(str.toString().trim());
		} catch (ParseException e) {
			log.error(e.getStackTrace());
			return null;
		}
		return paramdDate;
	}

	/**
	 * 页面对象转化为整数对象
	 * @param request
	 * @param key
	 * @return
	 */
	public int fmtToInt(HttpServletRequest request, String key) {
		log.debug("request will format to int: "+request.getParameter(key));
		
		Object str = request.getParameter(key);
		if (str == null || str =="") {
			return 0;
		}
		else {
			try {
				return Integer.parseInt(str.toString().trim());
			} catch (NumberFormatException e) {
				log.error(e.getStackTrace());
				return 0;
			}
		}
	}
	
	/**
	 * Object对象转化为整数对象
	 * @param request
	 * @param key
	 * @return
	 */
	public int fmtToInt(Object object) {
		log.debug("request will format to int: "+object);
		
		if (object == null || object =="") {
			return 0;
		}
		else {
			try {
				return Integer.parseInt(object.toString().trim());
			} catch (NumberFormatException e) {
				log.error(e.getStackTrace());
				return 0;
			}
		}
	}
	
	public Integer fmtToInteger(HttpServletRequest request, String key) {
		
		Object object = request.getParameter(key);
		if(object == null || object == "") {
			return null;
		} else {
			try {
				return Integer.parseInt(object.toString().trim());
			} catch (NumberFormatException e) {
				return null;
			}
		}
	}
	
	/**
	 * 页面对象转化为长整形对象
	 * @param request
	 * @param key
	 * @return
	 */
	public Long fmtToLong(HttpServletRequest request, String key) {
		log.debug("object will format to Long: "+request.getParameter(key));
		
		Object str = request.getParameter(key);
		if (str == null || str =="") {
			return null;
		}
		else {
			try {
				return Long.parseLong(str.toString().trim());
			} catch (NumberFormatException e) {
				log.error(e.getStackTrace());
				return new Long(-1);
			}
		}
	}
	
	/**
	 * Object对象转化为长整形对象
	 * @param request
	 * @param key
	 * @return
	 */
	public Long fmtToLong(Object object) {
		log.debug("object will format to Long: "+ object);
		
		if (object == null || object =="") {
			return null;
		}
		else {
			try {
				return Long.parseLong(object.toString().trim());
			} catch (NumberFormatException e) {
				log.error(e.getStackTrace());
				return new Long(-1);
			}
		}
	}
	
	
	/**
	 * 页面对象转化为Double对象
	 * @param request
	 * @param key
	 * @return
	 */
	public Double fmtToDouble(Object object){
		log.debug("object will format to Double: "+ object);
		
		if (object == null || object =="") {
			return null;
		}
		else {
			try {
				return Double.parseDouble(object.toString().trim());
			} catch (NumberFormatException e) {
				log.error(e.getStackTrace());
				return null;
			}
		}
	}
	
	/**
	 * 页面对象转化为Double对象
	 * @param request
	 * @param key
	 * @return
	 */
	public Double fmtToDouble(HttpServletRequest request, String key){
		log.debug("request will format to Double: "+request.getParameter(key));
		
		String str = this.fmtToString(request, key);
		
		if (str == null || str =="") {
			return null;
		}
		else {
			try {
				return Double.parseDouble(str);
			} catch (NumberFormatException e) {
				log.error(e.getStackTrace());
				return null;
			}
		}
	}
	
	// 避免xss跨站脚本
		public String HtmlFliter(String in){
			
			in = in.replaceAll("&", "&amp;");
			in = in.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
			in = in.replaceAll("\r", "");
			in = in.replaceAll("\n", "<br>");
			in = in.replaceAll("\"", "&quot;");
			in = in.replaceAll(" ", "&nbsp;");
			in = in.replaceAll("'", "&acute;");
			in = in.replaceAll("eval\\((.*)\\)", "");
			in = in.replaceAll("[\\\"\\\'][\\s]*((?i)javascript):(.*)[\\\"\\\']", "\"\"");
			//in = in.replaceAll("((?i)script)", "");
			
			return in;
		}
	
	/**
	 * 取出Shiro中的当前用户Id.
	 */
	protected Integer getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}
	
	public String getResource(String  key){
		try {
			return ResourceBundle.getBundle("config").getString(key);
		} catch (Exception e) {
			return "Can't find resource for bundle";
		}
	}
	
	public String trimString(String rawString) {
		return rawString.replaceAll("\"", "");
	}
	
	// 邮箱格式
	public Boolean checkEmailPattern(String email){
	    Pattern   pattern   =   Pattern.compile(REGEX_EMAIL);  
	    Matcher   matcher   =   pattern.matcher(email);  
	    return matcher.find();
	}
	
	// 电话格式
	public Boolean checkPhonePattern(String phone){
	    Pattern   pattern   =   Pattern.compile(REGEX_PHONE);  
	    Matcher   matcher   =   pattern.matcher(phone);  
	    return matcher.find();
	}
	
	// 昵称格式
	public Boolean checkNicknamePattern(String nickname){
	    Pattern   pattern   =   Pattern.compile(REGEX_NICKNAME);  
	    Matcher   matcher   =   pattern.matcher(nickname);  
	    return matcher.find();
	}
	
}
